//
//  TGTools.m
//  Customer
//
//  Created by tangang on 2017/8/23.
//  Copyright © 2017年 tangang. All rights reserved.
//

#import "TGTools.h"
#import <CoreLocation/CoreLocation.h>

@implementation TGTools
///颜色转图片
+(UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

//获取字符串的宽高
+(CGSize)boundingRectWithString:(NSString *)string withSize:(CGSize)size anfont:(CGFloat)fontSize{
    UIFont * tfont = [UIFont systemFontOfSize:fontSize];
    //高度估计文本大概要显示几行，宽度根据需求自己定义。 MAXFLOAT 可以算出具体要多高
    //    获取当前文本的属性
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 0;
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,style,NSParagraphStyleAttributeName,nil];
    //ios7方法，获取文本需要的size，限制宽度
    CGSize  actualsize =[string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:tdic context:nil].size;
    return actualsize;
}

+ (CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width andLineSpacing:(CGFloat)lineSpacing{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpacing;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.0f
                          };
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}


+ (CGFloat)boundingRectWithString:(NSString *)string withWidth:(CGFloat)width anfont:(UIFont *)font{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 0;
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,style,NSParagraphStyleAttributeName,nil];
    CGSize  actualsize =[string boundingRectWithSize:CGSizeMake(width, 30) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:tdic context:nil].size;
    return actualsize.width;
}

//字典转json
+ (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don"t care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        NSLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}


+ (NSDictionary *)JsonToDict:(NSString *)strJson{
    if (!strJson) {
        return nil;
    }
    
    
    NSData *jsonData = [strJson dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark----------------------------
+(void)checkOpenGPS:(UIViewController *)viewCtrl{
    ///检测是否打开定位
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:@"您没有打开定位，请前往设置界面将定位开启" preferredStyle:UIAlertControllerStyleAlert];
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [viewCtrl presentViewController:alertCtrl animated:YES completion:nil];
    }else if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied) {
        ///检测对本程序打开定位
        UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:@"您没有打开应用定位，请前往设置界面将定位开启" preferredStyle:UIAlertControllerStyleAlert];
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }]];
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [viewCtrl presentViewController:alertCtrl animated:YES completion:nil];
    }
}

+ (UIImage *)getSnapshotImage:(UIViewController *)vc{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(vc.view.window.frame), CGRectGetHeight(vc.view.window.frame)), NO, 1);
    [vc.view.window drawViewHierarchyInRect:CGRectMake(0, 0, CGRectGetWidth(vc.view.window.frame), CGRectGetHeight(vc.view.window.frame)) afterScreenUpdates:NO];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

+ (UIViewController*)viewController:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

+ (void)setViewFilletWithView:(UIView *)view andHaveBorder:(BOOL)isHave{
    view.layer.masksToBounds=YES;
    view.layer.cornerRadius=5;
    if (isHave) {
        view.layer.borderColor=DEFAULTLINECOLOR.CGColor;
        view.layer.borderWidth=1.0;
    }
}

+ (void)downloadImageWithUrl:(NSString *)url andSuccess:(void (^)(UIImage *))success{
    SDWebImageManager *manager = [SDWebImageManager sharedManager] ;
    [manager downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger   receivedSize, NSInteger expectedSize) {
        // progression tracking code
    }  completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,   BOOL finished, NSURL *imageURL) {
        if (image) {
            success([self image:image]);
        }
    }];
}



+ (CGSize)conversionsSize:(CGSize)size{
    CGSize currentSize=CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH/size.width*size.height);
    return currentSize;
}

+ (NSString *)getTime:(int)time{
    if (time<10) {
        return [NSString stringWithFormat:@"0%d",time];
    }
    return [NSString stringWithFormat:@"%d",time];
}


+(UIImage*)image:(UIImage *)image{
    
    if (image.size.width<SCREEN_WIDTH) {
        return image;
    }
    
    CGSize size=CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH/image.size.width*image.size.height);
    
    // 得到图片上下文，指定绘制范围
    UIGraphicsBeginImageContext(size);
    
    // 将图片按照指定大小绘制
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前图片上下文中导出图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 当前图片上下文出栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}
///生成随机GUID
+ (NSString*) stringWithUUID {
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString    *uuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
    return uuidString;
}

+ (UIImage *)compressionImage:(UIImage *)image{
    CGSize  size;
    if (image.size.height>image.size.width) {
        size=CGSizeMake(image.size.width*800/image.size.height, 800);
    }else{
        size=CGSizeMake(800, image.size.height*800/image.size.width);
    }
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}

+ (NSString *)base64WithImage:(UIImage *)image{
    NSData *data = UIImageJPEGRepresentation([self compressionImage:image], 0.6f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    encodedImageStr=[NSString stringWithFormat:@"data:image/jpeg;%@",encodedImageStr];
    return encodedImageStr;
}

+ (NSString *)dateFormatter:(NSString *)strTime andDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:strTime];
    NSString *str=[dateFormatter stringFromDate:date];
    return str;
}

+ (NSDate *)dateFormatter:(NSString *)formatter andString:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
//    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//    NSDate *dateFormatted = [dateFormatter dateFromString:time];
    NSDate *date=[dateFormatter dateFromString:time];
    return date;
}

+ (NSString *)getShengXiao:(NSString *)digit{
    NSString *s=@"";
    digit=(digit.length<2?[NSString stringWithFormat:@"0%@",digit]:digit);
    NSArray *chineseZodiacJsonData = @[@{@"BeginTime":@"20180216",@"EndTime":@"20190204",@"Data":@[@{@"Name":@"狗",@"Nums":@"01,13,25,37,49"},@{@"Name":@"鸡",@"Nums":@"02,14,26,38"},@{@"Name":@"猴",@"Nums":@"03,15,27,39"},@{@"Name":@"羊",@"Nums":@"04,16,28,40"},@{@"Name":@"马",@"Nums":@"05,17,29,41"},@{@"Name":@"蛇",@"Nums":@"06,18,30,42"},@{@"Name":@"龙",@"Nums":@"07,19,31,43"},@{@"Name":@"兔",@"Nums":@"08,20,32,44"},@{@"Name":@"虎",@"Nums":@"09,21,33,45"},@{@"Name":@"牛",@"Nums":@"10,22,34,46"},@{@"Name":@"鼠",@"Nums":@"11,23,35,47"},@{@"Name":@"猪",@"Nums":@"12,24,36,48"}]},@{@"BeginTime":@"20190205",@"EndTime":@"20200124",@"Data":@[@{@"Name":@"猪",@"Nums":@"01,13,25,37,49"},@{@"Name":@"狗",@"Nums":@"02,14,26,38"},@{@"Name":@"鸡",@"Nums":@"03,15,27,39"},@{@"Name":@"猴",@"Nums":@"04,16,28,40"},@{@"Name":@"羊",@"Nums":@"05,17,29,41"},@{@"Name":@"马",@"Nums":@"06,18,30,42"},@{@"Name":@"蛇",@"Nums":@"07,19,31,43"},@{@"Name":@"龙",@"Nums":@"08,20,32,44"},@{@"Name":@"兔",@"Nums":@"09,21,33,45"},@{@"Name":@"虎",@"Nums":@"10,22,34,46"},@{@"Name":@"牛",@"Nums":@"11,23,35,47"},@{@"Name":@"鼠",@"Nums":@"12,24,36,48"}]},@{@"BeginTime":@"20200125",@"EndTime":@"20210211",@"Data":@[@{@"Name":@"鼠",@"Nums":@"01,13,25,37,49"},@{@"Name":@"猪",@"Nums":@"02,14,26,38"},@{@"Name":@"狗",@"Nums":@"03,15,27,39"},@{@"Name":@"鸡",@"Nums":@"04,16,28,40"},@{@"Name":@"猴",@"Nums":@"05,17,29,41"},@{@"Name":@"羊",@"Nums":@"06,18,30,42"},@{@"Name":@"马",@"Nums":@"07,19,31,43"},@{@"Name":@"蛇",@"Nums":@"08,20,32,44"},@{@"Name":@"龙",@"Nums":@"09,21,33,45"},@{@"Name":@"兔",@"Nums":@"10,22,34,46"},@{@"Name":@"虎",@"Nums":@"11,23,35,47"},@{@"Name":@"牛",@"Nums":@"12,24,36,48"}]},@{@"BeginTime":@"20210212",@"EndTime":@"20220131",@"Data":@[@{@"Name":@"牛",@"Nums":@"01,13,25,37,49"},@{@"Name":@"鼠",@"Nums":@"02,14,26,38"},@{@"Name":@"猪",@"Nums":@"03,15,27,39"},@{@"Name":@"狗",@"Nums":@"04,16,28,40"},@{@"Name":@"鸡",@"Nums":@"05,17,29,41"},@{@"Name":@"猴",@"Nums":@"06,18,30,42"},@{@"Name":@"羊",@"Nums":@"07,19,31,43"},@{@"Name":@"马",@"Nums":@"08,20,32,44"},@{@"Name":@"蛇",@"Nums":@"09,21,33,45"},@{@"Name":@"龙",@"Nums":@"10,22,34,46"},@{@"Name":@"兔",@"Nums":@"11,23,35,47"},@{@"Name":@"虎",@"Nums":@"12,24,36,48"}]},@{@"BeginTime":@"20220201",@"EndTime":@"20230121",@"Data":@[@{@"Name":@"虎",@"Nums":@"01,13,25,37,49"},@{@"Name":@"牛",@"Nums":@"02,14,26,38"},@{@"Name":@"鼠",@"Nums":@"03,15,27,39"},@{@"Name":@"猪",@"Nums":@"04,16,28,40"},@{@"Name":@"狗",@"Nums":@"05,17,29,41"},@{@"Name":@"鸡",@"Nums":@"06,18,30,42"},@{@"Name":@"猴",@"Nums":@"07,19,31,43"},@{@"Name":@"羊",@"Nums":@"08,20,32,44"},@{@"Name":@"马",@"Nums":@"09,21,33,45"},@{@"Name":@"蛇",@"Nums":@"10,22,34,46"},@{@"Name":@"龙",@"Nums":@"11,23,35,47"},@{@"Name":@"兔",@"Nums":@"12,24,36,48"}]}];
    NSDate *date=[NSDate date];
    NSDateFormatter *formartter=[[NSDateFormatter alloc]init];
    formartter.dateFormat=@"yyyyMMdd";
    double time=[[formartter stringFromDate:date] doubleValue];
    for (NSDictionary *dict in chineseZodiacJsonData) {
        double begin=[[dict objectForKey:@"BeginTime"] doubleValue];
        double EndTime=[[dict objectForKey:@"EndTime"] doubleValue];
        if (time>=begin&&time<EndTime) {
            NSArray *arr=[dict objectForKey:@"Data"];
            for (NSDictionary *dictData in arr) {
                NSString *nums=[dictData objectForKey:@"Nums"];
                if ([nums containsString:digit]) {
                    s=[dictData objectForKey:@"Name"];
                    return s;
                }
            }
        }
    }
    
    return s;
}

@end
